<?php 
namespace app\app\model;
use think\Model;
use think\Db;

class UserCoupon extends Model{

	public $user_id;

	public function getAll($status){
		$where['a.status'] = array('eq',$status);
		$where['a.user_id']= array('eq',$this->user_id);
		$data = $this->alias('a')->join('coupon b','a.coupon_id=b.id','left')->field('a.id,a.status,b.exempt,b.max,b.start_time,b.end_time')->where($where)->select();
		if( !empty($data) ){
			foreach($data as $k => $v){
				$data[$k]['start'] = date('Y-m-d H:i:s',$v['start_time']);
				$data[$k]['end']   = date('Y-m-d H:i:s',$v['end_time']);
			}
		}
		return $data;
	}

	public function getOne($id,$total_price){
		$where['a.id'] = array('eq',$id);
		$where['a.status'] = array('eq',1);
		$coupon = $this->alias('a')->join('coupon b','a.coupon_id=b.id','left')->field('a.status,b.max,b.exempt,b.start_time,b.end_time')->where($where)->find();
		if( $coupon && $coupon['max'] <= $total_price){
			$total_price = $total_price - $coupon['exempt'];
		}
		return $total_price;
	}

}